import {Tree, Icon, Button, Row, Col} from 'antd'
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
import LwjButton from 'components/LwjButton/LwjButton'
import {debug} from 'util';

const TreeNode = Tree.TreeNode

const LwjTree = ({
  dataSource,
  multiple = false,
  checkable = false,
  defaultExpandAll = true,
  checkedExpand = false,
  canEdit = false,
  showLine = false,
  onCheck,
  onSelect,
  onAdd,
  onDelete
}) => {
  // 当选中的节点
  let currentSelectedNode = {}
  // 处理源数据,生成树形结构
  const dealedSourceData = (function loop(data) {
    let temp = []
    let lev = 0
    data.forEach((val, index) => {
      if (!val.parentId) {
        val.key = `0-${index}`
        data[index].key = `0-${index}`
        temp.push(val)
      }
    })

    // 查找子元素
    function findChild(temp) {
      temp.forEach((col, i) => {
        if (find(col.id).length > 0) {
          col.children = find(col.id)
          col
            .children
            .forEach((con, num) => {
              con.key = col.key + '-' + num
              data.forEach((val, index) => {
                if (val.id === con.id) {
                  val.key = col.key + '-' + num
                }
              })

            })
          findChild(col.children)
        }

      })
      return temp
    }

    // 看是否有子元素
    function find(id) {
      let temp = []
      data.forEach(v => {
        if (v.parentId === id) {
          temp.push(v)
        }
      })
      return temp
    }

    temp = findChild(temp)
    return ({data, temp})
  })(dataSource)

  // 获取默认选择值
  const getKeys = (data) => {
    let temp = []
    data.forEach((val) => {
      if (! val.children && val.id !== '0' && val.checked === 1) {
        temp.push(val.key)
      }
    })
    return temp
  }

  //处理原数据
  const loop = (data) => data.map((item) => {
    let customLabel = {}
    if (item.children) {
      return <TreeNode
        title={item.name}
        key={item.key}
        disabled={item.disabled}
        disableCheckbox={item.disableCheckbox}>{loop(item.children)}</TreeNode>
    }
    return <TreeNode
      title={item.name}
      key={item.key}
      disabled={item.disabled}
      disableCheckbox={item.disableCheckbox}/>
  })
  const treeNodes = loop(dealedSourceData.temp)

  // 选择节点预处理
  const pretreatCheck = (checkedKeys, info) => {
    /** @namespace info.halfCheckedKeys */
    const halfCheckedKeys = info.halfCheckedKeys || []
    checkedKeys = checkedKeys.concat(halfCheckedKeys)
    let temp = []
    dealedSourceData
      .data
      .forEach(val => {
        if (!_.isEmpty(checkedKeys) && checkedKeys.indexOf(val.key) !== -1) {
          temp.push(val);
        }
      })
    if (onCheck) {
      onCheck(temp)
    }
  }
  // 点击节点预处理
  const pretreatSelect = (selectedKeys) => {
    let selectedData = _.find(dealedSourceData.data, (d) => {
      return d.key === selectedKeys[0]
    })
    currentSelectedNode = selectedData
    if (onSelect) {
      onSelect(selectedData)
    }
  }

  // 点击添加预处理
  const pretreatAdd = () => {
    if (!_.isEmpty(currentSelectedNode)) {
      if (onAdd) {
        onAdd(currentSelectedNode)
      }
    } else {
      // TODO 之后再给错误提示框
      console.log('您还没选中任何的节点呀')
    }
  }

  // 点击删除预处理
  const pretreatDelete = () => {
    if (!_.isEmpty(currentSelectedNode)) {
      if (onDelete) {
        onDelete(currentSelectedNode)
      }
    } else {
      // TODO 之后再给错误提示框
      console.log('您还没选中任何的节点呀')
    }
  }

  const ColProps = {
    xs: 24,
    sm: 12,
    style: {
      marginBottom: 16
    }
  }

  const TwoColProps = {
    ...ColProps,
    xl: 96
  }

  return (
    <div>
      {canEdit && <Row gutter={24}>
        <Col {...ColProps}>
          <Button
            type="primary"
            size="small"
            className="margin-right"
            onClick={pretreatAdd}>添加</Button>
          <Button
            type="primary"
            size="small"
            className="margin-right"
            onClick={pretreatDelete}>删除</Button>
        </Col>
      </Row>}

      {dealedSourceData !== undefined && <Tree
        multiple={multiple}
        checkable={checkable}
        defaultExpandAll={true}
        defaultCheckedKeys={getKeys(dealedSourceData.data)}
        onCheck={pretreatCheck}
        onSelect={pretreatSelect}
        showLine={showLine}>
        {treeNodes}
      </Tree>
}

    </div>
  )
}

LwjTree.propTypes = {
  dataSource: PropTypes
    .arrayOf(PropTypes.shape({name: PropTypes.string.isRequired, id: PropTypes.string.isRequired, disabled: PropTypes.bool, disableCheckbox: PropTypes.bool}))
    .isRequired,
  multiple: PropTypes.bool,
  checkable: PropTypes.bool,
  defaultExpandAll: PropTypes.bool,
  checkedExpand: PropTypes.bool,
  onCheck: PropTypes.func,
  onSelect: PropTypes.func,
  canEdit: PropTypes.bool,
  onAdd: PropTypes.func,
  onDelete: PropTypes.func
}

export default LwjTree
